<template>
  <div class="page-container">
    <div class="card">
      <el-form label-width="70px">
        <el-form-item label="文章标题" class="title-label">
          <el-input size="small" placeholder="这里输入文章标题" v-model="formData.title"></el-input>
        </el-form-item>
      </el-form>
      <mavon-editor ref="mavon" class="markdown" :boxShadow="false" v-model="formData.content"></mavon-editor>
      <div class="publish-button">
        <el-button type="primary" icon="el-icon-s-promotion" size="mini" plain @click="handleOpen">发布文章</el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" plain @click="cancel">取消编辑</el-button>
      </div>
    </div>

    <el-drawer :visible="visible" :before-close="handleClose" :show-close="false" size="400px" :with-header="false">
      <div class="publish-container" v-loading="dialogLoading" element-loading-text="正在准备发布文章组件">
        <div class="publish-header">发布选项</div>
        <el-collapse v-model="activeNames">
          <el-form ref="articleForm" :model="formData" :rules="rules" size="small" hide-required-asterisk>
            <el-collapse-item title="博客分类/标签" name="1">
              <div class="custom-content">
                <el-form-item label="博客标签">
                  <el-popover placement="bottom-start" width="460" title="标签" trigger="click">
                    <TagsSelect ref="tagsSelect" @selectTags="selectTags" :activeTags="tags"/>
                    <el-tag slot="reference" v-for="tag in tags" :key="tag.value" class="tags-item" @close="handleRemoveTag(tag)" disable-transitions closable>
                      {{ tag.label }}
                    </el-tag>
                    <el-button icon="el-icon-plus" size="mini" slot="reference">添加博客标签</el-button>
                  </el-popover>
                </el-form-item>
                <el-form-item label="文章分类" prop="categoryId">
                  <el-select v-model="formData.categoryId" placeholder="请选择文章分类（必填）" size="small" clearable>
                    <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-collapse-item>
            <el-collapse-item title="常用选项" name="2">
              <div class="custom-content">
                <el-form-item label="博客封面" prop="cover">
                  <el-row>
                    <el-col :span="8">
                      <div class="cover" v-if="formData.cover">
                        <el-image :src="formData.cover" fit="contain"></el-image>
                        <div class="cover-remove">
                          <el-button type="text" icon="el-icon-delete" @click.stop="removeCover"></el-button>
                        </div>
                      </div>
                      <el-button v-else @click="editCover" icon="el-icon-picture-outline" size="mini">添加文章封面</el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-row>
                  <el-col :span="12">
                    <el-form-item>
                      <el-checkbox v-model="formData.isSticky">是否置顶</el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item>
                      <el-checkbox v-model="formData.allowComment">允许评论</el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item>
                      <el-checkbox v-model="formData.allowDonation">开启打赏</el-checkbox>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="文章摘要" prop="summary">
                  <el-input type="textarea" v-model="formData.summary" placeholder="请填写文章摘要，最多180字（必填）" :maxlength="180" :rows="3" show-word-limit/>
                </el-form-item>
              </div>
            </el-collapse-item>
            <el-collapse-item title="高级选项" name="3">
              <div class="custom-content">
                <el-form-item label="文章类型" prop="type">
                  <el-radio-group v-model="formData.type">
                    <el-radio v-for="dict in dict.type.blog_article_type" :key="dict.value" :label="dict.value"> {{ dict.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="原文链接" v-if="formData.type === '1' || formData.type === '2'" prop="originalLink">
                  <el-input size="small" placeholder="请填写原文链接（必填）" v-model="formData.originalLink"></el-input>
                </el-form-item>
                <el-form-item label="可见范围" prop="visibility">
                  <el-radio-group v-model="formData.visibility">
                    <el-radio v-for="dict in dict.type.blog_visible_type" :key="dict.value" :label="dict.value"> {{ dict.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </el-collapse-item>
          </el-form>
        </el-collapse>
        <div class="publish-footer">
          <el-button type="primary" :loading="buttonLoading" size="small" plain icon="el-icon-s-promotion" @click="submitForm(1)">立即发布</el-button>
          <el-button type="warning" :loading="buttonLoading" size="small" plain icon="el-icon-timer" @click="$refs.timeRelease.handleView()">定时发布</el-button>
          <el-button type="info" :loading="buttonLoading" icon="el-icon-document" size="small" plain @click="submitForm(0)">保存草稿</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 文件空间 -->
    <file-space
      :visible="coverVisible"
      @confirm="changeCover"
      :limit="1"
      :text="'只能上传 .jpeg .jpg .png .gif 格式的文件，且不超过2MB'"
      :accept="['.jpeg', '.jpg', '.png', '.gif']"
      :size="2"
      @close="closeFileSpace">
    </file-space>

    <!-- 定时发布 -->
    <time-release ref="timeRelease" @confirm="handlePublish"></time-release>
  </div>
</template>

<script>
import TimeRelease from '../TimeRelease.vue'
import FileSpace from '../../../../../components/FileSpace/index.vue'
import TagsSelect from '../../../../../components/TagsSelect/index.vue'
import { saveArticle } from '../../../../../api/blog/article'
import { listOptions } from '../../../../../api/blog/blog-category'

export default {
  name: 'ArticleCreate',

  dicts: ['blog_article_type', 'blog_visible_type'],

  components: { FileSpace, TagsSelect, TimeRelease },

  data () {
    return {
      // 页面标题
      activeNames: ['1', '2', '3'],
      // 显示发布文章对话框
      visible: false,
      // 发布文章加载框
      dialogLoading: false,
      // 文章表单对象
      formData: {
        // 文章标题
        title: undefined,
        // 文章分类
        categoryId: undefined,
        // 博客标签
        tags: [],
        // 文章封面
        cover: undefined,
        // 文章摘要
        summary: undefined,
        // 文章类型
        type: '0',
        // 可见范围
        visibility: '1',
        // 是否允许评论
        allowComment: true,
        // 是否开启打赏
        allowDonation: true,
        // 是否置顶
        isSticky: false,
        // 原文链接
        originalLink: undefined,
        // 发布时间
        publishTime: undefined
      },
      // 文章表单校验规则
      rules: {
        // 文章摘要
        summary: [{ required: true, message: '请填写文章摘要', trigger: 'blur' }],
        // 文章分类
        categoryId: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
        // 文章类型
        type: [{ required: true, message: '请选择文章类型', trigger: 'blur' }],
        // 原文链接
        originalLink: [{ required: true, message: '请填写原文链接', trigger: 'blur' }],
        // 可见范围
        visibility: [{ required: true, message: '请选择文章可见范围', trigger: 'blur' }]
      },
      // 文件空间对话框
      coverVisible: false,
      // 文章分类选项
      categoryOptions: [],
      // 博客标签
      tags: [],
      // 对话框按钮加载框
      buttonLoading: false
    }
  },

  mounted () {
    // 赋值当前页面内容
    this.title = this.$route.meta.title
    this.listCategoryOptions()
  },

  methods: {
    // 加载博客分类方法
    listCategoryOptions () {
      const that = this
      // 打开加载框
      that.dialogLoading = true
      // 获取博客分类
      listOptions().then((res) => {
        that.categoryOptions = res
        // 关闭加载框
        that.dialogLoading = false
      }).catch(() => {
        // 关闭加载框
        that.dialogLoading = false
      })
    },
    // 点击发布文章方法
    handleOpen () {
      this.visible = true
    },
    // 打开文件空间对话框
    editCover () {
      this.coverVisible = true
    },
    // 关闭文件选择框
    closeFileSpace () {
      this.coverVisible = false
    },
    // 更新分类封面
    changeCover (value) {
      this.formData.cover = value[0].src
    },
    // 关闭发布文章对话框方法
    handleClose () {
      // 关闭对话框
      this.visible = false
      this.reset()
    },
    // 重置表单
    reset () {
      // 清除校验条件
      this.formData = {
        // 文章标题
        title: undefined,
        // 文章分类
        categoryId: undefined,
        // 博客标签
        tags: [],
        // 文章封面
        cover: undefined,
        // 文章摘要
        summary: undefined,
        // 文章类型
        type: '0',
        // 文章状态
        status: undefined,
        // 可见范围
        visibility: '1',
        // 是否允许评论
        allowComment: true,
        // 是否开启打赏
        allowDonation: true,
        // 是否置顶
        isSticky: false,
        // 原文链接
        originalLink: undefined
      }
      this.tags = []
      // 清除表单校验
      this.resetForm('articleForm')
    },
    // 选择标签
    selectTags (tag) {
      if (this.tags.includes(tag)) {
        this.handleRemoveTag(tag)
      } else {
        if (this.tags.length === 5) {
          this.$message.warning('最多只能选择5个标签')
          return
        }
        this.tags.push(tag)
      }
    },
    // 移除博客标签
    handleRemoveTag (tag) {
      // 获取当前博客标签的索引
      const index = this.tags.indexOf(tag)
      this.tags.splice(index, 1)
    },
    // 清除当前文章封面方法
    removeCover () {
      this.formData.cover = undefined
    },
    // 发布文章方法
    submitForm (status) {
      if (!this.formData.title) {
        this.$message.error('文章标题不能为空')
        return
      }
      if (!this.formData.content) {
        this.$message.error('文章内容不能为空')
        return
      }
      if (this.tags.length === 0) {
        this.$message.error('博客标签不能为空')
        return
      }
      const that = this
      this.$refs.articleForm.validate(valid => {
        // 校验未通过则直接返回
        if (!valid) return
        that.formData.tags = []
        // 将博客标签ID添加到传输表单中
        that.tags.forEach(item => {
          that.formData.tags.push(item.value)
        })
        that.formData.status = status
        // 开启加载框
        that.buttonLoading = true
        that.dialogLoading = true
        // 提交文章数据
        saveArticle(that.formData).then((res) => {
          that.$message.success('文章发布成功')
          // 关闭加载框
          that.buttonLoading = false
          that.dialogLoading = false
          // 清除数据
          that.reset()
          // 关闭当前页面
          that.closeCurTags()
          // 跳转到文章发布成功页面
          that.$router.push('/article-content/article-success/' + res)
        }).catch(() => {
          // 关闭对话框
          that.buttonLoading = false
          that.dialogLoading = false
        })
      })
    },
    // 取消编辑方法
    cancel () {
      // 关闭当前标签页
      this.closeCurTags()
      // 跳转到文章管理页面
      this.$router.push('/blog/article')
    },
    // 关闭当前标签页方法
    closeCurTags () {
      // 获取当前路径
      const path = this.$route.fullPath
      // 获取当前标签页
      const tagsViewList = this.$store.getters.tagsViewList
      // 默认发布文章是最后一个标签页
      var index = tagsViewList.length - 1
      // 先获取到当前标签页的索引
      for (var i = 0; i < tagsViewList.length; i++) {
        const item = tagsViewList[i]
        // 遍历当前标签页数组
        if (item.fullPath === path) {
          // 找到当前页面对应索引并返回
          index = i
        }
      }
      // 关闭当前标签页
      this.$store.commit('app/REMOVE_TAGS_VIEW', {
        type: 'index',
        index
      })
    },
    // 确定定时发布时间
    handlePublish (value) {
      this.formData.publishTime = value
      console.log(value)
      // 发布定时文章
      this.submitForm(2)
    }
  }
}
</script>

<style lang="scss" scoped>
.markdown {
  min-height: calc(100vh - 285px);
}
.title-label {
  font-size: 25px;
  font-weight: 800;
}
.article-create-wrapper {
  padding: 10px 30px;
}
.tags-item {
  margin-bottom: 0.5rem;
  margin-right: 0.5rem;
}
.cover {
  position: relative;
  .el-image {
    border-radius: 5px;
  }
  .el-button {
    color: #fff;
  }
}
.cover-remove {
  position: absolute;
  left: 0;
  top: 0;
  height: calc(100% - 10px);
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #00000080;
  border-radius: 5px;
  opacity: 0;
  transition: opacity 0.3s cubic-bezier(0.55, 0, 0.1, 1);
}
.cover:hover .cover-remove {
  opacity: 1;
}
.form-row {
  display:flex;
  flex-wrap: wrap;
}
.publish-button {
  width: 100%;
  margin-top: 1.25rem;
  text-align: right;
}
.publish-container {
  position: relative;
  width: 100%;
  padding-top: 1rem;
  padding-bottom: 1rem;

  .el-select {
    width: 100%;
  }
  .publish-header {
    padding-left: 1rem;
    margin-bottom: 1rem;
    font-weight: 500;
  }
  .publish-footer {
    display: flex;
    justify-content: center;
    margin-top: 1.5rem;
  }
  .custom-content {
    padding: 1rem 1rem 0 1rem; /* 设置内容区域内边距 */
  }
}
</style>
